﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using CLEX.AdminUI.Service;

namespace CLEX.AdminUI.ViewModel
{
    internal sealed class UserCreateVM : ViewModelBase
    {
        private readonly Facade facade;
        private RelayCommand create;
        private RelayCommand cancel;
        private UserData user = new UserData();

        public ICommand Create
        {
            get
            {
                if (create == null)
                {
                    create = new RelayCommand(DoCreate);
                }
                return create;
            }
        }

        public ICommand Cancel
        {
            get
            {
                if (cancel == null)
                {
                    cancel = new RelayCommand(DoCancel);
                } 
                return cancel;
            }
        }

        public string Username
        {
            get { return user.Username; }
            set
            {
                if (user.Username != value)
                {
                    user.Username = value;
                    FirePropertyChanged("Username");
                }
            }
        }

        public string Email
        {
            get { return user.Email; }
            set
            {
                if (user.Email != value)
                {
                    user.Email = value;
                    FirePropertyChanged("Email");
                }
            }
        }

        public bool IsAdmin
        {
            get { return user.IsAdmin; }
            set
            {
                if (user.IsAdmin != value)
                {
                    user.IsAdmin = value;
                    FirePropertyChanged("IsAdmin");
                }
            }
        }

        public UserCreateVM(Facade facade)
        {
            this.facade = facade;
        }

        private void DoCreate()
        {
            try
            {
                facade.CreateUser(user);
            }
            catch (Exception ex)
            {
                facade.ShowError("An unexpected error occured while creating the user.", ex);
                return;
            }
            FireCloseRequested();
        }

        private void DoCancel()
        {
            FireCloseRequested();
        }
    }
}
